import * as loginService from '@/api/login'





/**
 * 转换树形结构
 * @param list 源数组
 * @param tree 树
 * @param parentId 父ID
 */
const listToTree = (list, tree, parentId) => {
  list.forEach(item => {
    // 判断是否为父级菜单
    if (item.parentId === parentId) {
      const child = {
        ...item,
        key: item.key || item.name,
        children: []
      }
      
      // 迭代 list，找到当前菜单相符合的所有子菜单
      listToTree(list, child.children, item.id)
      // 删掉不存在 children 属性
      if (child.children.length <= 0) {
        delete child.children
      }
      // push child
      tree.push(child)
    }
  })
}

/**
 * 动态生成菜单
 * @param token
 * @returns {Promise<Router>}
 */
export const generatorDynamicRouter = token => {
  return new Promise((resolve, reject) => {
    
    loginService.userNav(token).then(res => {
      const result  = res.data
      const menuNav = []
      const childrenNav = []
      debugger
      // 后端数据, 根级树数组,根级 PID
      listToTree(result, childrenNav, '0')
      // rootRouter.children = childrenNav
      menuNav.push(childrenNav)
      resolve(childrenNav)
    }).catch(err => {
      reject(err)
    })
  })
}

